package com.hsylient.javase.chapter14.jwt;

import cn.hutool.core.codec.Base64Decoder;
import cn.hutool.core.codec.Base64Encoder;
import cn.hutool.core.date.DateUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.alibaba.fastjson.JSONObject;

import java.util.Objects;

public class JWTDetail {
    public static void main(String[] args) {

        // JWT的头部
        JSONObject header = new JSONObject();
        // alg属性表示签名的算法（algorithm）默认是 HMAC SHA256（写成 HS256
        header.put("alg", "HS256");
        // typ属性表示这个令牌（token）的类型（type），JWT令牌统一写为JWT
        header.put("typ", "JWT");

        // JWT的载荷
        JSONObject payload = new JSONObject();
        // 签发人
        payload.put("iss", "hsylient");
        // 过期时间
        payload.put("exp", DateUtil.parse("2023-11-30 00:00:00"));
        // 主题
        payload.put("sb", "主题");
        // 生效时间
        payload.put("nbf", DateUtil.now());
        // 签发时间
        payload.put("iat", DateUtil.parse("2023-11-29 00:00:00"));
        // 编号
        payload.put("jti", System.currentTimeMillis());

        // 自定义字段
        payload.put("愿望","找个妹妹");

        // JWT的签名部分，将头部和签名加上中间的 . 进行sha256签名算法
        byte[] digestByte = DigestUtil.sha256(header + "." + payload);

        // 使用URL安全的base64编码
        String jwt = Base64Encoder.encodeUrlSafe(Objects.toString(header)) + "." + Base64Encoder.encodeUrlSafe(Objects.toString(payload)) + "." + Base64Encoder.encodeUrlSafe(digestByte);

        // eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyLmhL_mnJsiOiLmib7kuKrlprnlprkiLCJuYmYiOiIyMDIzLTExLTMwIDAwOjA0OjE1IiwiaXNzIjoiaHN5bGllbnQiLCJleHAiOiIyMDIzLTExLTMwIDAwOjAwOjAwIiwiaWF0IjoiMjAyMy0xMS0yOSAwMDowMDowMCIsImp0aSI6MTcwMTI3Mzg1NTk3Nywic2IiOiLkuLvpopgifQ.hyt9Oi3DO1Um5BWAXJQbHG-qrkIHxhWdelhKL36sCGg
        System.out.println(jwt);

        // ------------------------解谜--------------------------------

        // payload:eyLmhL_mnJsiOiLmib7kuKrlprnlprkiLCJuYmYiOiIyMDIzLTExLTMwIDAwOjA0OjE1IiwiaXNzIjoiaHN5bGllbnQiLCJleHAiOiIyMDIzLTExLTMwIDAwOjAwOjAwIiwiaWF0IjoiMjAyMy0xMS0yOSAwMDowMDowMCIsImp0aSI6MTcwMTI3Mzg1NTk3Nywic2IiOiLkuLvpopgifQ
        byte[] decodePayload = Base64Decoder.decode("eyLmhL_mnJsiOiLmib7kuKrlprnlprkiLCJuYmYiOiIyMDIzLTExLTMwIDAwOjA0OjE1IiwiaXNzIjoiaHN5bGllbnQiLCJleHAiOiIyMDIzLTExLTMwIDAwOjAwOjAwIiwiaWF0IjoiMjAyMy0xMS0yOSAwMDowMDowMCIsImp0aSI6MTcwMTI3Mzg1NTk3Nywic2IiOiLkuLvpopgifQ");

        // {"愿望":"找个妹妹","nbf":"2023-11-30 00:04:15","iss":"hsylient","exp":"2023-11-30 00:00:00","iat":"2023-11-29 00:00:00","jti":1701273855977,"sb":"主题"}
        System.out.println(new String(decodePayload));

    }
}
